//package com.wl.gateway.filter;
//
//import com.wl.common.core.constant.HttpConstants;
//import com.wl.common.core.constant.SecurityConstants;
//import com.wl.common.core.utils.StringUtils;
//import com.wl.gateway.utils.WebFluxUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//
///**
// * @author: wanglin
// * @date: 2024-03-06 周三
// * @Version: 1.0
// * @Description:
// */
//@Component
//public class AuthFilter2 implements GlobalFilter, Ordered {
//    private static final Logger log = LoggerFactory.getLogger(AuthFilter2.class);
//
//    /**
//     * 排除过滤的 uri 地址，nacos自行添加
//     */
////    @Autowired
////    private IgnoreWhiteProperties ignoreWhite;
//
////    @Autowired
////    private RedisService redisService;
//
////    @Autowired
////    private IgnoreUrlsProperties ignoreUrlList;
//
////    @Autowired
////    private JwtTokenUtil jwtTokenUtil;
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpRequest.Builder mutate = request.mutate();
//
//        String url = request.getURI().getPath();
//        // 跳过不需要验证的路径
////        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
////            return chain.filter(exchange);
////        }
////        String token = getToken(request);
////        if (StringUtils.isEmpty(token)) {
////            return unauthorizedResponse(exchange, "令牌不能为空");
////        }
////
////        String currentUrl = request.getURI().getPath();
////
////        Claims claims = JwtUtils.parseToken(token);
////        if (claims == null)
////        {
////            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
////        }
//
//        // 不需要保护的资源路径允许访问,这里主要是针对放行接口并携带了token的路径，则直接放行；如：注册接口，带了token；
////        PathMatcher pathMatcher = new AntPathMatcher();
////        for (String url : ignoreUrlList.getUrls()) {
////            if (pathMatcher.match(url, currentUrl)) {
////                return chain.filter(exchange.mutate().request(mutate.build()).build());
////            }
////        }
////        String token = jwtTokenUtil.getToken();
////
////        //1-判断token
////        if (StringUtils.isBlank(token)) {
////            return unauthorizedResponse(exchange, "令牌不能为空，未登录，请登录!");
////        }
////
////        //2-判断是否能从token中获取用户名，token是否正确
////        String username = jwtTokenUtil.getUserName(token);
////        if (StringUtils.isBlank(username)) {
////            return unauthorizedResponse(exchange, "用户名为空，未登录，请登录!");
////        }
//
////        //3-内存中是否存在该登录用户，一般存储在Redis，（这里登录用户保存在内存中）
////        LoginUserDetails loginUser = jwtTokenUtil.getLoginUser(username);
////        if (ObjUtil.isNull(loginUser)) {
////            return unauthorizedResponse(exchange, "未登录，请登录!");
////        }
////        String userKey = jwtTokenUtil.getUserKey(token);
////        //验证token是否和用户token一致;根据toke中的user_key标识验证
////        if (!loginUser.getToken().equals(userKey)) {
////            return unauthorizedResponse(exchange, "无效token，请登录!");
////        }
////
////        //token 存在用户名，但未登录
////        if (Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
////            //若已经登录，则设置 UsernamePasswordAuthenticationToken 认证对象，后面过滤器链会根据是否验证是否进行判断，重新设置用户对象
////            UsernamePasswordAuthenticationToken authenticationToken =
////                    new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), loginUser.getAuthorities());
////            authenticationToken.setDetails(loginUser);
////            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
////        }
//
////        Claims claims = JwtUtils2.parseToken(token);
////        if (claims == null) {
////            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
////        }
////        String userkey = JwtUtils.getUserKey(claims);
////        boolean islogin = redisService.hasKey(getTokenKey(userkey));
////        if (!islogin) {
////            return unauthorizedResponse(exchange, "登录状态已过期");
////        }
////        String userid = JwtUtils.getUserId(claims);
////        String username = JwtUtils.getUserName(claims);
////        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
////            return unauthorizedResponse(exchange, "令牌验证失败");
////        }
////
////        // 设置用户信息到请求
////        addHeader(mutate, SecurityConstants.USER_KEY, userkey);
////        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
////        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
////        // 内部请求来源参数清除
////        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
//        return chain.filter(exchange.mutate().request(mutate.build()).build());
//    }
//
//    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
//        if (value == null) {
//            return;
//        }
//        String valueStr = value.toString();
//        String valueEncode = WebFluxUtils.urlEncode(valueStr);
//        mutate.header(name, valueEncode);
//    }
//
//    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
//        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
//    }
//
//    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
//        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
//        return WebFluxUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpConstants.UNAUTHORIZED);
//    }
//
//    /**
//     * 获取缓存key
//     */
//    private String getTokenKey(String token) {
////        return CacheConstants.LOGIN_TOKEN_KEY + token;
//        return null;
//    }
//
//    /**
//     * 获取请求token
//     */
//    private String getToken(ServerHttpRequest request) {
//        String token = request.getHeaders().getFirst(SecurityConstants.AUTHENTICATION);
//        // 如果前端设置了令牌前缀，则裁剪掉前缀
//        if (StringUtils.isNotEmpty(token) && token.startsWith(SecurityConstants.TOKEN_PREFIX)) {
//            token = token.replaceFirst(SecurityConstants.TOKEN_PREFIX, StringUtils.EMPTY);
//        }
//        return token;
//    }
//
//    @Override
//    public int getOrder() {
//        return -200;
//    }
//}
